package com.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.demo.common.LoginUser;
import com.demo.domain.User;
import com.demo.mapper.MenuMapper;
import com.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //根据username查用户信息
        LambdaQueryWrapper<User> ulqw = new LambdaQueryWrapper<>();
        ulqw.eq(User::getUserName,username);
        User user = userMapper.selectOne(ulqw);

        //获取到对象为空,抛出异常
        if (Objects.isNull(user)){
            //后面交给authenticationEntryPoint的实现类处理，抛出“认证失败异常”
            throw new RuntimeException("用户名或者密码错误");
        }

        //获取权限信息
        List<String> list = menuMapper.selectPermsByUserId(user.getId());
//        List<String> list = new ArrayList<>(Arrays.asList("test"));//写死的权限信息
        //将用户信息封装成UserDetails对象
        return new LoginUser(user,list);
    }
}
